package com.zhuangwei.sell.controller;

import com.zhuangwei.sell.dataobject.ProductCategory;
import com.zhuangwei.sell.dataobject.ProductInfo;
import com.zhuangwei.sell.service.CategoryService;
import com.zhuangwei.sell.service.ProductService;
import com.zhuangwei.sell.utils.ResultVoUtil;
import com.zhuangwei.sell.vo.ProductInfoVo;
import com.zhuangwei.sell.vo.ProductVo;
import com.zhuangwei.sell.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 买家商品
 *
 * @author LeviCoder
 * @create 2019-02-28 23:21
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultVo list() {

        // 1.查询所有的上架商品
        List<ProductInfo> productInfoList = productService.findUpAll();

        // 2.查询类目（一次性查询）
        List<Integer> categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
        List<ProductCategory> byCategoryTypeIn = categoryService.findByCategoryTypeIn(categoryTypeList);

        // 3.数据拼装
        List<ProductInfoVo> productInfoVoList = new ArrayList<>();
        for (ProductCategory category : byCategoryTypeIn) {
            ProductVo productVo = new ProductVo();
            productVo.setCategoryName(category.getCategoryName());
            productVo.setCategoryType(category.getCategoryType());

            ArrayList<ProductInfoVo> infoVoArrayList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList) {
                if (productInfo.getCategoryType().equals(category.getCategoryType())){
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productInfo,productInfoVo);
                    infoVoArrayList.add(productInfoVo);
                }
            }
            productVo.setProductInfoVoList(infoVoArrayList);
        }
        return ResultVoUtil.success(productInfoVoList);
    }
}
